import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { UserFootprintEntity } from '../entity/footprint';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GoodsInfoEntity } from '../../goods/entity/info';

@Provide()
export class UserFootprintService extends BaseService {
    @InjectEntityModel(UserFootprintEntity)
    footprintEntity: Repository<UserFootprintEntity>;

    @InjectEntityModel(GoodsInfoEntity)
    goodsEntity: Repository<GoodsInfoEntity>;

    /**
     * 记录用户足迹
     */
    async recordFootprint(userId: number, goodsId: number) {
        // 获取商品信息
        const goods = await this.goodsEntity.findOne({
            where: { id: goodsId }
        });

        if (!goods) {
            throw new Error('商品不存在');
        }

        // 检查是否已有足迹记录
        const exist = await this.footprintEntity.findOne({
            where: { userId, goodsId }
        });

        if (exist) {
            // 更新访问次数和最后访问时间
            await this.footprintEntity.update(exist.id, {
                visitCount: exist.visitCount + 1,
                lastVisitTime: new Date()
            });
        } else {
            // 创建新的足迹记录
            await this.footprintEntity.save({
                userId,
                goodsId,
                lastVisitTime: new Date()
            });
        }
    }
} 